﻿using System;
using System.Diagnostics;
using TimeSnapperPluginAPI;

namespace SqlExecuterPlugin
{
    public class SqlExecuterPlugin : ITimeSnapperPlugin
    {
        private IServices m_services;
        private QueryToolMenuItem m_mi;

        bool ITimeSnapperPlugin.Configurable
        {
            get { return false; }
        }

        void ITimeSnapperPlugin.Configure()
        {
            // NADA
        }

        string ITimeSnapperPlugin.Description
        {
            get { return "A tool to execute arbitrary SQL statements against TimeSnapper FireBird database." + System.Environment.NewLine + System.Environment.NewLine +
                "The tool can be accessed from the Tools menu on TimeSnapper main dialog."; }
        }

        string ITimeSnapperPlugin.FriendlyName
        {
            get { return "SQL Executer"; }
        }

        object ITimeSnapperPlugin.HandleEvent(TimeSnapperEvent timeSnapperEvent, IServices services, EventArgs args)
        {
            m_services = services;
            m_mi.Services = services;
            return null;
        }

        TimeSnapperMenuItem[] ITimeSnapperPlugin.MenuItems()
        {
            // retain a reference to the menu item because we need to assign the "Services" when we 
            // get the chance (since it hasn't been populated at this point).  We need to wait for the
            // plugin loaded event first.
            m_mi = new QueryToolMenuItem(TimeSnapperMenu.MainFormTools, "Query Tool");
            return new TimeSnapperMenuItem[] { m_mi };
        }

        Guid ITimeSnapperPlugin.PluginID
        {
            get { return new Guid("F913E113-0177-409B-BC0E-3B05782050DF"); }
        }

        TimeSnapperEvent[] ITimeSnapperPlugin.SubscribesTo()
        {
            // must subscribe to one event at least to grab a hold of the services object.
            return new TimeSnapperEvent[] { TimeSnapperEvent.PluginsLoaded };
        }
    }

    public class QueryToolMenuItem : TimeSnapperMenuItem
    {
        public IServices Services;

        public QueryToolMenuItem(TimeSnapperMenu belongsTo, string text)
            : base(belongsTo, text)
        {
        }

        public override void Click(object sender, EventArgs e)
        {
            base.Click(sender, e);
            QueryForm qf = new QueryForm(Services);
            qf.Show();
        }
    }
}
